package com.bauer.base.thread;


public class Mylock {

    private boolean islock  = false;

    private Object obj =  new Object();

    /**
     * 第一个线程进入不需要等待所以返回false 在没有并发的情况下每次执行都是不会锁住的 这里可能会理解出现问题
     * 这是自旋锁
     * @throws Exception
     */
    public synchronized void lock() throws Exception{
        while(islock){
            this.wait();
        }
        islock= true;
    }


    public synchronized void unlock(){
        this.notify();
        islock = false;
    }


    public static void main(String[] args) {
        Counter counter =  new Counter();
        Runnable runnable = new MyRunnable(counter);
        Thread thread1 = new Thread(runnable);
        Thread thread2 = new Thread(runnable);
        thread1.start();
        thread2.start();
    }

    static class MyRunnable implements Runnable{

        private Counter counter;

        public MyRunnable(Counter counter) {
            this.counter = new Counter();
        }

        @Override
        public void run() {
            for (int j = 0 ;j<30;j++){
                //线程不安全
//                System.out.println(counter.add(1));
                //采用synchronized关键字使得线程安全
//                System.out.println(counter.add(1));
                //简单实现的自旋锁
//                try {
//                    System.out.println(counter.addSafeBuyMulock(1));
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
                //简单实现的自旋锁可重入锁
                try {
                    System.out.println(counter.addSafeBuyMyReenTrantLock(1));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
    }

}
